package com.xb.loan.util.ftp;

import java.io.File;
import java.util.Vector;

import com.xb.loan.util.log.DefaultLoggerFacotry;
import com.xb.loan.util.log.LogFormatUtil;
import org.slf4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SftpUtil {
	
    private Logger log = DefaultLoggerFacotry.getLogger(FtpUtil.class);

    private String host;
    
    private int port;
    
    private String username;
    
    private String password;
    
    private int timeout = 30000;
    
	public static void main(String[] args) throws Exception{
		System.out.println(new File("C:\\Users\\lottery\\Downloads\\天边-.mp3").getParentFile().getAbsolutePath());
		System.out.println(new File("C:\\Users\\lottery\\Downloads\\天边-.mp3").getName());
//		new SftpUtil("192.168.1.25",22,"v31","v31",30000).uploadFile("d:\\", "/home/v31/plat/upload/", "u.txt");
//		new SftpUtil("192.168.1.25",22,"v31","v31",30000).downloadFile("/home/v31/plat/upload", "d:\\", "d.txt");
		System.out.println("/home/v31/plat/upload/qq.txt".substring(0,"/home/v31/plat/upload/qq.txt".lastIndexOf("/")+1));
		System.out.println("/home/v31/plat/upload/qq.txt".substring("/home/v31/plat/upload/qq.txt".lastIndexOf("/")+1));
	}
	
	public SftpUtil(String host, int port, String username, String password, int timeout){
		
		this.host = host;
		this.port = port;
		this.username = username;
		this.password = password;
		this.timeout = timeout;
	} 
	
	private ChannelSftp connect()  throws Exception{
		
		Session session = null;
		Channel channel = null;
		JSch jsch = new JSch();
		
		if(port <=0){
			//连接服务器，采用默认端口
			session = jsch.getSession(username, host);
		}else{
			//采用指定的端口连接服务器
			session = jsch.getSession(username, host ,port);
		}
		//如果服务器连接不上，则抛出异常
		if (session == null) {
			throw new Exception("session is null");
		}
		
		//设置登陆主机的密码
		session.setPassword(password);//设置密码   
		//设置第一次登陆的时候提示，可选值：(ask | yes | no)
		session.setConfig("StrictHostKeyChecking", "no");
		//设置登陆超时时间   
		session.connect(timeout);
		
		//创建sftp通信通道
		channel = (Channel) session.openChannel("sftp");
		channel.connect(1000);
		return (ChannelSftp) channel;
	}
	
	private void close(Channel channel) throws Exception{
		
		if(channel.getSession() != null){
			
			channel.getSession().disconnect();
		}
		if(channel != null){
			
			channel.disconnect();
		}
	}
	
	public boolean uploadFile(String localFileDir, String remoteFileDir, String fileName) {

		ChannelSftp sftp = null;
		String localFilePath = localFileDir + File.separator + fileName;
		try {
			
			sftp = this.connect();
			Vector<LsEntry> vector = null;
			try {
				
				vector = (Vector<LsEntry>)sftp.ls(remoteFileDir);
			} catch (Exception e) {
				
				if(vector == null){
					sftp.mkdir(remoteFileDir);
				}
			}
			
			sftp.put(localFilePath, remoteFileDir);
		}catch (Exception e) {
			
			e.printStackTrace();
			return false;
		}finally {
			
			try {
				this.close(sftp);
			} catch (Exception e) {
				
				log.info(LogFormatUtil.getFormatTemplate(new String[]{"module","message"}),
	            		new Object[]{"SftpUtil.uploadFile","upload " + localFilePath + " close failure!"});   
				e.printStackTrace();
			}
		}
		return true;
	}
	
	public boolean downloadFile(String remoteFileDir, String localFileDir, String fileName){
		
		ChannelSftp sftp = null;
		String localFilePath = localFileDir + File.separator + fileName;
		String remoteFilePath = remoteFileDir;
		if(remoteFileDir.contains("/")){
			remoteFilePath = remoteFilePath + "/" + fileName;
		}else{
			remoteFilePath = remoteFilePath + "\\" + fileName;
		}
		
		try {
			sftp = this.connect();
	        // 看文件夹是否存在，不存在则创建
	        File localDir = new File(localFileDir);
	        if (!localDir.exists()) {
	        	localDir.mkdirs();
	        }
	        
	        //判断远程文件是否存在
			Vector<LsEntry> vector = null;
			try {
				
				vector = (Vector<LsEntry>)sftp.ls(remoteFilePath);
			} catch (Exception e) {
				
				if(vector == null){
					
					log.info(LogFormatUtil.getFormatTemplate(new String[]{"module","remoteFilePath","message"}),
		            		new Object[]{"SftpUtil.downloadFile",remoteFilePath,"remote file does not exist!"});   
		            return false;
				}
			}
	        
	        //下载
			sftp.get(remoteFilePath, localFileDir);
			File downloadFile = new File(localFilePath);
			
			//判断是否下载正常
			if(downloadFile.exists()){
				long remoteFileSize = vector.get(0).getAttrs().getSize();
				long dwonloadFileSize = downloadFile.length();
				if(remoteFileSize != dwonloadFileSize){
					
					log.info(LogFormatUtil.getFormatTemplate(new String[]{"module","remoteFilePath","message"}),
		            		new Object[]{"SftpUtil.downloadFile",remoteFilePath,
									remoteFileSize + " not the same size as download file " + dwonloadFileSize});   
					downloadFile.delete();
					return false;
				}
			}else{
				
				log.info(LogFormatUtil.getFormatTemplate(new String[]{"module","remoteFilePath","message"}),
	            		new Object[]{"SftpUtil.downloadFile",remoteFilePath,"local file is not exist!"});  
				return false;
			}
				
		}catch (Exception e) {
			
			e.printStackTrace();
			return false;
		}finally {
			
			try {
				this.close(sftp);
			} catch (Exception e) {
				
				log.info(LogFormatUtil.getFormatTemplate(new String[]{"module","message"}),
	            		new Object[]{"SftpUtil.downloadFile","download " + remoteFilePath + " close failure!"});   
				e.printStackTrace();
			}
		}
		return true;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
	
}
